#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__='meng'

import asyncio

@asyncio.coroutine
def create_pool(loop,**kw):
	logging.info('create database connection pool....')
	global __pool
	__pool = yield from aiomysql.create_pool(
		host = kw.get('host','localhost'),
		port = kw.get('port',3306),
		user = kw['user'],
		password = kw['password'],
		db = kw['db'],
		charset = kw.get('charset','utf-8'),
		autocommit = kw.get('autocommit',Ture),
		maxsize = kw.get('maxsize',10),
	)

@asyncio.coroutine
def select(sql,args,size=None):
	log(sql,args)
	global __pool
	with (yield from __pool) as conn:
		cur = yield from conn.cursor(aiomysql.DictCursor)
		yield from cur.execute(sql.replace('?','%s'),args or ())
		if size:
			rs = yield from cur.fectchmany(size)
		else:
			rs = yield from cur.fetc
		yield from cur.close()
		logging.info('rows returned:%s' % len(rs))
		return rs

@asyncio.coroutine
def execute(sql,args):
	log(sql)
	with (yield from __pool) as conn:
		try:
			cur = yield from conn.cursor()
			yield from cur.execute(sql.replace('?','%s'),args)
			affected = cur.rowcount
			yield from cur.close()
		except Exception as e:
			raise
		return affected